<?php

namespace App\Http\Controllers\Business;

use App\Models\AdminUser;
use App\Models\Manager;
use App\Models\VerifyCode;
use Illuminate\Auth\Authenticatable;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class RegisterController extends Controller
{

    use AuthenticatesUsers;
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 注册渠道经理
     */
    public function index()
    {
        return redirect("/wap/login");
         if(Session::get('wechat'))
         {
             $openid = Session::get('wechat.oauth_user.default.original.openid');

             //查询用户绑定记录
            $info = Manager::where(['wx_userinfo->openid'=>$openid])->first();
            if($info)
            {
                Session::put('manager.id',$info->id);
                Session::save();
               return redirect(url('product'));
            }
         }else{
             $openid = 'not exist';
         }
         return view('business.Register.index',compact('openid'));
    }

    /**
     * @param Request $request
     * 保存渠道经理
     */
    public function store(Request $request)
    {
        $validate = Validator::make($request->all(),[
            'name' => 'required|min:1',
            'phone' => 'required|min:11|max:11',
            'password' => 'required|min:6|max:20',
            'type' => 'required'
        ]);
        if(!$validate->fails()) {
            if($request->type == 'person' || ($request->type == 'company' && $request->companyName))
            {
                $info = Session::get('wechat.oauth_user.default.original');

                $exist = Manager::where(['phone'=>$request->phone])
                        ->first();
                if (!count($exist)) {//无绑定记录
                    $type = $request->type == 'company' ?  1 : 2;//1公司2个人
                    $invite_id = 0;//邀请人id
                    $invite_code = $this->generateCode();//生成邀请码
                    if($request->inviteCode){
                        $invite = $exist = Manager::where(['invitation_code' => $request->inviteCode])->first();
                        if($invite)
                        {
                            $invite_id = $invite->id;
                        }
                    }
                   $insert =  Manager::create(['name'=>$request->name,'phone'=>$request->phone,'password'=>bcrypt($request->password),'type'=>$type,'company'=>$request->companyName,'invitation_code'=>$invite_code,'parent_mid'=>$invite_id,'status'=>1,'wx_userinfo'=>$info]);
                    if(!$insert)
                    {
                        $this->set('code',1);
                        $this->set('message','系统错误');
                    }
                    Session::put('manager.phone',$insert->phone);
                    Session::put('manager.id',$insert->id);
                    Session::put('manager.name',$insert->name);
                    Session::save();
                } else {
                    //已经绑定过
                    $this->set('code',1);
                    $this->set('message','重复绑定');
                }
            }else{
                $this->set('code',1);
                $this->set('message','请填写公司名字');
            }
        }
        else{
            $this->set('code',1);
            $this->set('message','参数不正确');
        }
        return $this->ajaxResponse();
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 登录：页面
     */
    public function login()
    {
        return view('business.Register.login');
    }
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 登录:验证
     */
    public function loginCheck(Request $request)
    {
        $validate = Validator::make($request->all(),[
           'phone' => 'required|min:11|max:11',
           'password' => 'required|min:6|max:20'
        ]);
        if(!$validate->fails()) {
            $exist = Manager::where(['phone'=>$request->phone])->first();
            if($exist) {
                if (Auth::attempt(['phone' => $request->phone, 'password' => $request->password])) {
                    $wxinfo = Session::get('wechat.oauth_user.default.original');
                    //登录成功：
                    $info = Manager::where(['phone' => $request->phone])
                        ->first();
                    if($info->status==1) {
                        if ($info->wx_userinfo==null && $wxinfo) {
                            $update = Manager::where(['id' => $info->id])->update(['wx_userinfo' => json_encode($wxinfo)]);
                            if (!$update) {
                                $this->set('code', 1);
                                $this->set('message', '系统错误');
                            }
                        }
                        Session::put('manager.phone', $info->phone);
                        Session::put('manager.name', $info->name);
                        Session::put('manager.id', $info->id);
                        Session::save();
                    }else{
                        $this->set('code',1);
                        $this->set('message','账户被禁用');
                    }
                } else {
                    $this->set('code',1);
                    $this->set('message','密码不正确');
                }
            }else{
                $this->set('code',1);
                $this->set('message','用户未注册');
            }
        }
        else{
            $this->set('code',1);
            $this->set('message','参数不正确');
        }
        return $this->ajaxResponse();
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 忘记密码：页面
     */
    public function forgot()
    {
        return view('business.Register.forgot');
    }

    /**
     * @param Request $request
     * 重置密码
     */
    public function resetPassword(Request $request)
    {
        $validate = Validator::make($request->all(),[
            'mobile' => 'required|min:11|max:11',
            'password' => 'required|min:6|max:20',
        ]);
        if(!$validate->fails())
        {
            //验证成功
            $update = Manager::where(['phone'=>$request->mobile])
                ->update(['password'=>bcrypt($request->password)]);
            if(!$update)
            {
                $this->set('code',1);
                $this->set('message','系统错误');
            }else{
                $this->set('message','修改成功');
            }
        }else{
            $this->set('code',1);
            $this->set('message','参数不正确');
        }
        return $this->ajaxResponse();
    }
    /**
     * @return string
     * 生成邀请码
     */
    public function generateCode()
    {
        $str="QWERTYUPASDFGHJKLZXCVBNM23456789qwertyuipasdfghjkzxcvbnm";
        str_shuffle($str);
        $code = substr(str_shuffle($str),0,5);
        $exist = Manager::where(['invitation_code'=>$code])->first();
        if($exist)
        {
            $this->generateCode();
        }else{
            return $code;
        }
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * 登出
     */
    public function logout()
    {
        Session::flush();
        return redirect(url('wap/login'));
    }


}
